import Vue from 'vue'
import VueRouter from 'vue-router'

import { getToken } from '@/utils/storage'

// 1. 引入一级路由对应的页面组件
const Register = () => import('@/views/Register')
const Login = () => import('@/views/Login')
const Layout = () => import('@/views/Layout')
const Detail = () => import('@/views/Detail')

// 2. 引入二级路由对应的页面组件
const Article = () => import('@/views/Article')
const Collect = () => import('@/views/Collect')
const Like = () => import('@/views/Like')
const User = () => import('@/views/User')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/register', component: Register },
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirect: '/article',
      children: [
        { path: 'article', component: Article },
        { path: 'collect', component: Collect },
        { path: 'like', component: Like },
        { path: 'user', component: User }
      ]
    },
    { path: '/detail/:id', component: Detail }
  ]
})

// 3. 添加路由全局前置守卫
// 访问所有路径要去的页面, 都会经过这个全局前置守卫
// to: 要去的页面对应的路由对象
// from: 来的页面对应的路由对象
// next: 放行函数  next() 直接放行  next('路径') 拦截去路径对应的页面
router.beforeEach((to, from, next) => {
  const token = getToken()
  const whiteList = ['/login', '/register']
  // 3.1 判断是否有token
  if (token) {
    // 3.2 有token则直接放行
    next()
  } else {
    // 3.3 没有token, 判断是否在白名单
    if (whiteList.includes(to.path)) {
      // 在白名单, 直接放行
      next()
    } else {
      // 不在白名单, 拦截去登录页
      next('/login')
    }
  }
})

export default router
